<template>
	<view class="profile-container">
		<view class="user-header">
			<view class="user-info">
				<button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image :src="userInfo.avatar || '/static/images/default-avatar.png'" class="avatar"></image>
					<view class="edit-badge">编辑</view>
				</button>
				<view class="user-detail">
					<view class="nickname-wrapper" @click="showNicknameInput = true" v-if="!showNicknameInput">
						<view class="nickname">{{ userInfo.nickname || '未登录' }}</view>
						<text class="edit-hint">点击编辑</text>
					</view>
					<view class="nickname-input-wrapper" v-if="showNicknameInput">
						<input 
							type="nickname" 
							class="nickname-input" 
							placeholder="请输入昵称" 
							v-model="tempNickname"
							@blur="updateNickname"
							focus
						/>
					</view>
					<view class="login-btn" @tap="login" v-if="!isLoggedIn">点击登录</view>
				</view>
			</view>
		</view>
		
		<view class="stat-board">
			<view class="stat-item">
				<view class="stat-num">{{ stats.bloodSugarRecords }}</view>
				<view class="stat-text">血糖记录</view>
			</view>
			<view class="stat-item">
				<view class="stat-num">{{ stats.reminders }}</view>
				<view class="stat-text">健康提醒</view>
			</view>
			<view class="stat-item">
				<view class="stat-num">{{ stats.posts }}</view>
				<view class="stat-text">社区贴文</view>
			</view>
		</view>
		
		<view class="menu-list">
			<view class="menu-group">
				<view class="menu-item" @tap="navigate('/pages/profile/edit')">
					<view class="menu-icon profile-icon"></view>
					<view class="menu-text">个人资料</view>
					<view class="menu-arrow"></view>
				</view>
				<view class="menu-item" @tap="navigate('/pages/profile/healthReport')">
					<view class="menu-icon health-icon"></view>
					<view class="menu-text">健康报告</view>
					<view class="menu-arrow"></view>
				</view>
				<view class="menu-item" @tap="navigate('/pages/profile/dataExport')">
					<view class="menu-icon export-icon"></view>
					<view class="menu-text">数据导出</view>
					<view class="menu-arrow"></view>
				</view>
			</view>
			
			<view class="menu-group">
				<view class="menu-item" @tap="navigate('/pages/profile/settings')">
					<view class="menu-icon settings-icon"></view>
					<view class="menu-text">系统设置</view>
					<view class="menu-arrow"></view>
				</view>
				<view class="menu-item" @tap="navigate('/pages/profile/about')">
					<view class="menu-icon about-icon"></view>
					<view class="menu-text">关于我们</view>
					<view class="menu-arrow"></view>
				</view>
				<view class="menu-item" @tap="navigate('/pages/profile/feedback')">
					<view class="menu-icon feedback-icon"></view>
					<view class="menu-text">意见反馈</view>
					<view class="menu-arrow"></view>
				</view>
			</view>
			
			<view class="menu-group" v-if="isLoggedIn">
				<view class="menu-item logout" @tap="handleLogout">
					<view class="menu-text">退出登录</view>
				</view>
			</view>
		</view>
	</view>
	<custom-tabbar></custom-tabbar>
</template>

<script setup>
	import { ref, reactive } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { getUserInfo as getStoredUserInfo, getUserProfile, updateUserAvatar, updateUserNickname } from '../../common/utils/auth.js'
	import { updateUserInfo, logout, updateAvatarToBackend } from '../../common/api/user.js'
	
	// 用户信息
	const userInfo = ref({
		isLogin: false,
		nickname: '未登录',
		avatar: '/static/images/default-avatar.png'
	})
	
	// 临时存储编辑中的昵称
	const tempNickname = ref('')
	const showNicknameInput = ref(false)
	
	// 是否已登录
	const isLoggedIn = ref(false)
	
	// 统计数据
	const stats = ref({
		bloodSugarRecords: 0,
		reminders: 0,
		posts: 0
	})
	
	// 获取用户信息
	const loadUserInfo = () => {
		// 获取本地存储中的用户信息
		const storedUserInfo = getStoredUserInfo()
		console.log('获取到的本地用户信息:', storedUserInfo)
		
		if (storedUserInfo) {
			userInfo.value = {
				...userInfo.value,
				...storedUserInfo,
				isLogin: true
			}
			tempNickname.value = storedUserInfo.nickname || ''
			isLoggedIn.value = true
		} else {
			// 检查是否有userProfile
			const userProfile = getUserProfile()
			if (userProfile) {
				userInfo.value = {
					...userInfo.value,
					nickname: userProfile.nickName || '未登录',
					avatar: userProfile.avatarUrl || '/static/images/default-avatar.png',
					isLogin: false
				}
				tempNickname.value = userProfile.nickName || ''
			}
		}
	}
	
	// 选择头像
	const onChooseAvatar = async (e) => {
		if (!isLoggedIn.value) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}
		
		const avatarUrl = e.detail.avatarUrl
		console.log('选择的头像:', avatarUrl)
		
		try {
			// 显示加载提示
			uni.showLoading({
				title: '更新头像中...',
				mask: true
			})
			
			// 更新头像
			userInfo.value.avatar = avatarUrl
			
			// 更新本地存储
			updateUserAvatar(avatarUrl)
			
			// 更新到后端
			await updateAvatarToBackend(avatarUrl)
			
			uni.hideLoading()
			uni.showToast({
				title: '头像更新成功',
				icon: 'success'
			})
		} catch (error) {
			console.error('头像更新失败:', error)
			uni.hideLoading()
			uni.showToast({
				title: '头像更新失败',
				icon: 'none'
			})
		}
	}
	
	// 更新昵称
	const updateNickname = async () => {
		if (!isLoggedIn.value) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			showNicknameInput.value = false
			return
		}
		
		if (!tempNickname.value.trim()) {
			uni.showToast({
				title: '昵称不能为空',
				icon: 'none'
			})
			return
		}
		
		if (tempNickname.value.trim() === userInfo.value.nickname) {
			showNicknameInput.value = false
			return
		}
		
		try {
			// 显示加载提示
			uni.showLoading({
				title: '更新昵称中...',
				mask: true
			})
			
			// 更新本地显示
			userInfo.value.nickname = tempNickname.value.trim()
			
			// 更新本地存储
			updateUserNickname(tempNickname.value.trim())
			
			// 更新到后端
			await updateUserInfo({
				nickname: tempNickname.value.trim()
			})
			
			uni.hideLoading()
			uni.showToast({
				title: '昵称更新成功',
				icon: 'success'
			})
		} catch (error) {
			console.error('昵称更新失败:', error)
			uni.hideLoading()
			uni.showToast({
				title: '昵称更新失败',
				icon: 'none'
			})
		} finally {
			showNicknameInput.value = false
		}
	}
	
	// 登录
	const login = () => {
		uni.navigateTo({
			url: '/pages/login/index'
		})
	}
	
	// 退出登录
	const handleLogout = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: async (res) => {
				if (res.confirm) {
					await logout()
					userInfo.value = {
						isLogin: false,
						nickname: '未登录',
						avatar: '/static/images/default-avatar.png'
					}
					isLoggedIn.value = false
					uni.showToast({
						title: '已退出登录',
						icon: 'success'
					})
				}
			}
		})
	}
	
	// 导航到指定页面
	const navigate = (url) => {
		if (!isLoggedIn.value && url !== '/pages/profile/about' && url !== '/pages/profile/feedback') {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			return
		}
		
		uni.navigateTo({
			url: url,
			fail: (err) => {
				console.error('导航失败:', err)
				uni.showToast({
					title: '该功能将在后续完善',
					icon: 'none'
				})
			}
		})
	}
	
	// 加载统计数据
	const loadStats = () => {
		// 这里应该调用API获取统计数据
		// 使用Mock数据
		stats.value = {
			bloodSugarRecords: isLoggedIn.value ? 28 : 0,
			reminders: isLoggedIn.value ? 5 : 0,
			posts: isLoggedIn.value ? 3 : 0
		}
	}
	
	// 页面加载时获取数据
	onLoad(() => {
		loadUserInfo()
		loadStats()
	})
	
	// 每次页面显示时重新加载数据
	onShow(() => {
		loadUserInfo()
		loadStats()
	})
</script>

<style lang="scss">
	.profile-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 120rpx;
		
		.user-header {
			background-color: #8cc9a1;
			padding: 40rpx 30rpx;
			
			.user-info {
				display: flex;
				align-items: center;
				
				.avatar-btn {
					background: none;
					margin: 0;
					padding: 0;
					line-height: 1;
					overflow: visible;
					position: relative;
					
					&::after {
						border: none;
					}
					
					.edit-badge {
						position: absolute;
						bottom: 0;
						right: 0;
						background-color: rgba(0, 0, 0, 0.5);
						color: #fff;
						font-size: 20rpx;
						padding: 4rpx 8rpx;
						border-radius: 10rpx;
					}
				}
				
				.avatar {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					background-color: #fff;
					margin-right: 30rpx;
				}
				
				.user-detail {
					flex: 1;
					
					.nickname-wrapper {
						display: flex;
						align-items: center;
						margin-bottom: 10rpx;
						
						.nickname {
							font-size: 36rpx;
							color: #fff;
							font-weight: bold;
							margin-right: 15rpx;
						}
						
						.edit-hint {
							font-size: 22rpx;
							color: rgba(255, 255, 255, 0.7);
							background: rgba(255, 255, 255, 0.2);
							padding: 2rpx 10rpx;
							border-radius: 20rpx;
						}
					}
					
					.nickname-input-wrapper {
						margin-bottom: 10rpx;
						
						.nickname-input {
							background: rgba(255, 255, 255, 0.9);
							border-radius: 30rpx;
							height: 60rpx;
							font-size: 30rpx;
							color: #333;
							padding: 0 20rpx;
							width: 300rpx;
						}
					}
					
					.login-btn {
						font-size: 26rpx;
						color: rgba(255, 255, 255, 0.8);
						background-color: rgba(255, 255, 255, 0.2);
						display: inline-block;
						padding: 4rpx 20rpx;
						border-radius: 30rpx;
					}
				}
			}
		}
		
		.stat-board {
			display: flex;
			background-color: #fff;
			padding: 30rpx 0;
			margin-bottom: 20rpx;
			
			.stat-item {
				flex: 1;
				text-align: center;
				border-right: 1px solid #f0f0f0;
				
				&:last-child {
					border-right: none;
				}
				
				.stat-num {
					font-size: 36rpx;
					color: #8cc9a1;
					font-weight: bold;
					margin-bottom: 10rpx;
				}
				
				.stat-text {
					font-size: 24rpx;
					color: #666;
				}
			}
		}
		
		.menu-list {
			.menu-group {
				background-color: #fff;
				margin-bottom: 20rpx;
				
				.menu-item {
					display: flex;
					align-items: center;
					padding: 30rpx;
					border-bottom: 1px solid #f0f0f0;
					
					&:last-child {
						border-bottom: none;
					}
					
					.menu-icon {
						width: 40rpx;
						height: 40rpx;
						margin-right: 20rpx;
						background-size: cover;
					}
					
					.profile-icon {
						background-image: url('/static/images/icons/profile.png');
					}
					
					.health-icon {
						background-image: url('/static/images/icons/health.png');
					}
					
					.export-icon {
						background-image: url('/static/images/icons/export.png');
					}
					
					.settings-icon {
						background-image: url('/static/images/icons/settings.png');
					}
					
					.about-icon {
						background-image: url('/static/images/icons/about.png');
					}
					
					.feedback-icon {
						background-image: url('/static/images/icons/feedback.png');
					}
					
					.menu-text {
						flex: 1;
						font-size: 30rpx;
						color: #333;
					}
					
					.menu-arrow {
						width: 16rpx;
						height: 16rpx;
						border-top: 2rpx solid #ccc;
						border-right: 2rpx solid #ccc;
						transform: rotate(45deg);
					}
					
					&.logout {
						justify-content: center;
						
						.menu-text {
							flex: 0;
							color: #ff6b6b;
						}
					}
				}
			}
		}
	}
</style> 